<template>
  <Modal
    v-model="form.visible"
    :width="1000"
    :mask-closable="false"
    :loading="loading"
    :title="form.data.id ? '修改活动奖励' : '新增活动奖励'"
    ok-text="提交"
    @on-ok="ok">
    <Row class="mt30">
      <Col span="16" offset="4">
        <Form ref="form" :model="form.data" :rules="ruleValidate" :label-width="150">
          <FormItem prop="pkActGroup" label="组别">
            <Select
              v-model="form.data.pkActGroup"
              remote
              :remote-method="getActGroup"
              :loading="actGroupLoading">
              <Option v-for="(option, index) in actGroupList" :value="'' + option.pk_act_group" :key="index">{{option.group_name}}</Option>
            </Select>
          </FormItem>
          <FormItem prop="actRanking" label="顺序">
            <Select v-model="form.data.actRanking" style="width: 100%" placeholder="请选择顺序">
              <Option
                v-for="item in actSortCodeList"
                :key="item.code"
                :value="item.code">
                {{ item.name }}
              </Option>
            </Select>
          </FormItem>
          <FormItem prop="rankingName" label="名次(名称)">
            <Input v-model="form.data.rankingName" placeholder="请输入"></Input>
          </FormItem>
          <FormItem prop="reardName" label="奖品">
            <Input v-model="form.data.reardName" placeholder="请输入"></Input>
          </FormItem>
          <FormItem prop="reardNum" label="奖品数量">
            <InputNumber :max="9999" v-model.number="form.data.reardNum" placeholder="请输入"></InputNumber>
          </FormItem>
          <FormItem prop="reardImage" label="奖品图片">
            <upload-img v-if="form.visible" @on-change="onUploadImg" :defaultImageList="defaultImageList"></upload-img>
          </FormItem>
          <FormItem prop="reardRule" label="奖励规则">
            <Input type="textarea" v-model="form.data.reardRule" placeholder="请输入" :rows="4"></Input>
          </FormItem>
        </Form>
      </Col>
    </Row>
  </Modal>
</template>

<script>
  import Vue from 'vue'
  import { mapGetters } from 'vuex'
  import uploadImg from '@/components/upload-img'
  import activityApi from '@/api/activity'

  export default {
    name: 'update-modal',
    props: [
      'form'
    ],
    components: {
      uploadImg
    },
    data () {
      return {
        loading: true,
        actGroupLoading: false,
        actGroupList: [],
        ruleValidate: {
          pkActGroup: [
            { required: true, message: '请选择组别', trigger: 'change' }
          ],
          actRanking: [
            { required: true, type: 'number', message: '请选择顺序', trigger: 'change' }
          ],
          rankingName: [
            { required: true, message: '请输入名次(名称)', trigger: 'change' },
            { max: 50, message: '名次(名称)字符长度应小于50', trigger: 'change' }
          ],
          reardName: [
            { required: true, message: '请输入奖品', trigger: 'change' },
            { max: 50, message: '名次(名称)字符长度应小于50', trigger: 'change' }
          ],
          reardNum: [
            { required: true, type: 'number', message: '请输入奖品数量', trigger: 'change' }
          ],
          reardImage: [
            { required: true, message: '请上传奖励图片', trigger: 'change' }
          ],
          reardRule: [
            { max: 100, message: '奖励规则字符长度应小于100', trigger: 'change' }
          ]
        }
      }
    },
    computed: {
      ...mapGetters({
        userInfo: 'userInfo',
        actSortCodeList: 'actSortCodeList'
      })
    },
    watch: {
      'form.visible': 'onClose'
    },
    methods: {
      ok () {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.submitForm()
          } else {
            this.$Message.error('表单验证失败，请检查输入内容!')
            this.form.visible = true
            this.loading = false
            setTimeout(() => {
              this.loading = true
            }, 100)
          }
        })
      },
      onClose (isVisible) {
        if (!isVisible) {
          this.$nextTick(() => {
            this.$refs.form.resetFields()
          })
        } else {
          this.defaultImageList = Vue.filter('splitImg')(this.form.data.reardImage || '')
          this.getActGroup()
        }
      },
      onUploadImg (imgList) {
        this.form.data.reardImage = imgList.filter((item) => {
          return item.name.length > 0
        }).map((item) => {
          if (item.response && item.response.responseData) {
            return item.response.responseData
          } else {
            return item.name
          }
        }).join(',')
        this.$refs.form.validateField('reardImage')
      },
      async submitForm () {
        let activityId = this.$route.params.activityId
        this.form.data.pkActBaseInfo = activityId
        if (this.form.data.id) {
          const { body } = await activityApi.reward.update(this.form.data)
          if (this.$apiHelper.requestSuccessed(body.responseCode)) {
            this.$Message.info('修改成功')
            this.form.visible = false
            this.$emit('submit')
          } else {
            setTimeout(() => {
              this.$Modal.error({
                title: '错误',
                content: body.desc,
                onOk: () => {}
              })
              this.loading = false
            }, 500)
          }
        } else {
          const { body } = await activityApi.reward.create(this.form.data)
          if (this.$apiHelper.requestSuccessed(body.responseCode)) {
            this.$Message.info('保存成功')
            this.form.visible = false
            this.$emit('submit')
          } else {
            setTimeout(() => {
              this.$Modal.error({
                title: '错误',
                content: body.desc,
                onOk: () => {}
              })
              this.loading = false
            }, 500)
          }
        }
      },
      async getActGroup () {
        this.actGroupLoading = true
        const { body } = await activityApi.group.list({
          pk_act_base_info: this.$route.params.activityId,
          currentPage: 1,
          limit: 10
        })
        const { responseData } = body
        this.actGroupList = responseData.content
        this.actGroupLoading = false
      }
    },
    async mounted () {
      this.$store.dispatch('getCode', 'act_sort')
      await this.getActGroup()
    }
  }
</script>
